﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.IO;

namespace JEng_Mark_1.GameComponents
{
    public class JLogEntry
    {
        private DateTime _timeStamp;
        private string _message;
        private bool _error;

        public DateTime TimeStamp { get { return _timeStamp; } }
        public string Message { get { return _message; } }
        public bool IsError { get { return _error; } }

        public JLogEntry(string message, bool iserror)
        {
            _timeStamp = DateTime.Now;
            _message = message;
            _error = iserror;
        }

        public override string ToString()
        {
            return "[" + this.TimeStamp.ToString("HH:mm:ss") + "] " + this.Message;
        }
    }
        
    public class JLog
    {
        private static List<JLogEntry> _entries = new List<JLogEntry>();

        /// <summary>
        /// Construct a new log
        /// </summary>
        public JLog() { }

        /// <summary>
        /// Save the log to a file
        /// </summary>
        public static void Save()
        {
            TextWriter log = new StreamWriter("Content/log.txt", false);
            foreach (JLogEntry line in _entries)
            {
                log.WriteLine(line.ToString());
            }
            log.Close();
        }

        /// <summary>
        /// Add a new message to the log
        /// </summary>
        /// <param name="newMessage">Message to add</param>
        public static void addMessage(string newMessage)
        {
            _entries.Add(new JLogEntry(newMessage,false));
        }

        /// <summary>
        /// Add a new error message to the log
        /// </summary>
        /// <param name="newError">Error message to add</param>
        public static void addError(string newError)
        {
            _entries.Add(new JLogEntry(newError, true));
        }

        /// <summary>
        /// Get the latest message added to the log
        /// </summary>
        /// <returns>The last message on the log, or null if the log is empty</returns>
        public static JLogEntry getLastMessage()
        {
            if (_entries.Count == 0) return null;
            return _entries[_entries.Count - 1];
        }

        /// <summary>
        /// Returns a copy of the last count messages in the log
        /// </summary>
        /// <param name="count">Number of messages to retrieve</param>
        /// <returns>The last count messages in the log, or null if the log is empty</returns>
        public static JLogEntry[] getLastMessages(int count)
        {
            if (_entries.Count == 0) return null;
            List<JLogEntry> subColl = _entries.GetRange(_entries.Count - count, count);
            return subColl.ToArray();
        }


    }
}
